
package com.gitee.jmash.oidc.oauth2.impl;

import org.eclipse.microprofile.jwt.JsonWebToken;
import com.gitee.jmash.oidc.oauth2.enums.GrantType;
import com.gitee.jmash.oidc.oauth2.enums.GrantWay;
import com.gitee.jmash.oidc.oauth2.models.ClientCredentialsModel;
import com.gitee.jmash.oidc.oauth2.models.ErrorResponse;
import com.gitee.jmash.oidc.oauth2.models.TokenResponse;
import com.gitee.jmash.oidc.web.Constant;
import com.gitee.jmash.oidc.web.OidcMapper;
import com.gitee.jmash.rbac.RbacFactory;
import com.gitee.jmash.rbac.entity.TokenEntity;
import com.gitee.jmash.rbac.utils.TokenUtil;
import com.xyvcard.ops.OpsFactory;
import com.xyvcard.ops.entity.OpsClientEntity;
import jakarta.enterprise.context.Dependent;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.ws.rs.core.Response;

/**
 * OAuth 2.0 更新令牌.
 *
 * @author CGD
 *
 */
@Dependent
public class ClientCredentialsImpl {

  /** client_credentials --> access_token. */
  public Response token(@Valid ClientCredentialsModel token, HttpServletRequest request) {
    // 1.验证GrantType
    if (!GrantType.client_credentials.equals(token.getGrantType())) {
      return ErrorResponse.createResponse("invalid_grant", "invalid_grant不匹配.");
    }
    // 2.验证clientId、clientSecret
    OpsClientEntity client = OpsFactory.getOpsClientRead(Constant.TENANT)
        .findBySecret(token.getClientId(), token.getClientSecret());
    if (client == null || !client.allowGrantWay(GrantWay.client_credentials.name())) {
      return ErrorResponse.createResponse("invalid_client", "client_id身份认证错误或授权方式不一致.");
    }

    // 4.生成并记录AccessToken
    JsonWebToken webToken =
        TokenUtil.createClientToken(Constant.TENANT, token.getClientId(), token.getScope());
    TokenEntity tokenEntity = RbacFactory.getUserWrite(Constant.TENANT).clientToken(webToken,
        token.getClientId(), token.getScope());

    TokenResponse resp = new TokenResponse();
    OidcMapper.INSTANCE.update(resp, tokenEntity);

    return Response.ok().entity(resp).build();
  }
}
